package com.lxl.securitypermission.config;

import com.lxl.securitypermission.config.custom.CustomAccessDecisionManager;
import com.lxl.securitypermission.config.custom.CustomAccessDeniedHandler;
import com.lxl.securitypermission.config.custom.CustomAuthenticationFailureHandler;
import com.lxl.securitypermission.config.custom.CustomAuthenticationSuccessHandler;
import com.lxl.securitypermission.config.custom.CustomPermissionSource;
import com.lxl.securitypermission.config.custom.CustomUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * @author 绫小路
 * @date 2020/12/29 22:36
 * @description
 */
@Slf4j
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled =true) //使用注解授权
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired  // 登录成功，自定义返回结果
  private CustomAuthenticationSuccessHandler authenticationSuccessHandler;
  @Autowired  //  登录失败返，自定义返回结果
  private CustomAuthenticationFailureHandler authenticationFailureHandler;

  //加密的方式，spring5+以上必须要加密密码，这是官网推荐的加密方式
  @Autowired
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Autowired
  private CustomUserDetailsService customUserDetailsService;
  //实现细粒度鉴权
  @Autowired
  private CustomPermissionSource customPermissionSource;
  @Autowired
  private CustomAccessDecisionManager customAccessDecisionManager;
  @Autowired
  private CustomAccessDeniedHandler customAccessDeniedHandler;

  @Bean
  public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setHideUserNotFoundExceptions(false); //允许抛出UserNotFoundException异常
    provider.setUserDetailsService(customUserDetailsService);
    provider.setPasswordEncoder(passwordEncoder());
    return provider;
  }


  //认证----自定义认证
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //自定义认证
    auth.authenticationProvider(authenticationProvider());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    //授权规则，实现细粒度鉴权
    http.authorizeRequests()
        .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
          @Override
          public <O extends FilterSecurityInterceptor> O postProcess(O object) {
            object.setSecurityMetadataSource(customPermissionSource);
            object.setAccessDecisionManager(customAccessDecisionManager);
            return object;
          }
        });

    //自定义登陆返回的结果，用于ajax异步
    http.formLogin().successHandler(authenticationSuccessHandler)
        .failureHandler(authenticationFailureHandler).permitAll();

    //注销功能 ,跳回首页
    //关闭跨域认证请求，否则你需要post来注销
    http.logout().logoutSuccessUrl("/")
        .and().csrf().disable()
        .headers().frameOptions().disable();//允许使用iframe

    //启动登陆页面
    //定制登陆页面，表单提交的路径loginProcessingUrl
    http.formLogin().loginPage("/login").loginProcessingUrl("/login");

    //自定义403页面
    http.exceptionHandling().accessDeniedHandler(customAccessDeniedHandler);

  }


}
